<template>
  <div class="page">
    <div class="bg-box flex-center-between">
      <img src="@/assets/images/firecracker.gif" alt="">
      <img src="@/assets/images/firecracker.gif" alt="">
    </div>
    <div class="ercode" v-show="type == 1||type == 2">
        <img :src='qrcode' alt="">
        <p @click="testOnClick">微信扫码参与抽奖</p>
      </div>
    <div class="online" v-show="type == 1">
      <div class="circulate"
          v-if="seamlessScroll">
        <SeamlessScroll
          :data="allUserList"
          :class-option="classOption4"
          class="warp"
          ref="SeamlessScroll"
          >
          <div class="ul-item" >
            <div class="li-item" v-for="(item, index) in allUserList" :key="index">
              <img :src='item.headImgUrl' alt="">
            </div>
          </div>
        </SeamlessScroll>
      </div>
      <div class="online-bottom">
        <div>当前参与人数 {{ allUserList.length }} 人</div>
        <div class="btn main" @click="type = 2">开始</div>
      </div>
    </div>
    <!-- 准备抽奖-->
    <div class="start mask" v-show="type == 2||type===3">
      <div class="title-box flex-center-center">
        <i class="icon-arrow el-icon-arrow-left points" @click="changePrize('-')" v-show="type===2"></i>
        <div class="title">{{ prizeInfo[prizeIndex].name }}</div>
        <i class="icon-arrow el-icon-arrow-right points" @click="changePrize('+')" v-show="type===2"></i>
      </div>
      <template v-if="type == 2">
        <div class="prize">
          <img :src='prizeInfo[prizeIndex].img' alt="">
        </div>
        <div class="bottom-btn-box flex-center-between">
          <div class="left flex-center">
            <div class="pick">
              一次抽取
              <div class="pick-box flex-center">
                <i class="el-icon-minus points" @click="chooseNum('-')"></i>
                <div class="num">{{num}}</div>
                <!-- <div type="number" min="1" max="5"  oninput="if(value>5)value=5;if(value<1)value=1" v-model="num"> -->
                <i class="el-icon-plus points" @click="chooseNum('+')"></i>
              </div>
              人
            </div>
          </div>
          <div class="center-btn">
            <div class="btn main" @click="goRandom">开始</div>
          </div>
          <div class="right flex-center-end">
            <div @click="type = 4" class="points">已中奖名单（{{winnerList.length}}）人</div>
            <div class="back points" @click="type = 1">返回</div>
          </div>
        </div>
      </template>
      <template v-if="type == 3">
        <div class="roll">
          <div class="rotate flex-center-center" >
            <div class="user flex-column-center" v-for="item in num" :key="item">
              <img :src='randomUserList[showUser[item-1]].headImgUrl' alt="">
              <div class="name ellipsis">{{randomUserList[showUser[item-1]].nickName}}</div>
              <!-- <div>{{ [showUser[item-1]] }}</div> -->
            </div>
          </div>
          <div class="bottom-btn-box flex-center-between">
              <div class="left"></div>
              <div class="center-btn" v-show="!startRandomFlag">
                  <div class="btn main" @click="startRandom" @keyup.enter="startRandom">开始</div>
                  <!-- <input type="text" ref="inputdata" @keydown.enter="startRandom" class="hiddenIpt"> -->
              </div>
              <div class="center-btn" v-show="startRandomFlag">
                <div class="btn main" :class="lotteryStatus?'disabled':''" @click="stopRandom">停止</div>
                <!-- <input type="text" ref="inputdata" @keydown.enter="stopRandom" class="hiddenIpt"> -->
              </div>
              <div class="right flex-center-end">
                <div class="back points" @click="backChoose" v-show="!startRandomFlag">返回</div>
              </div>
          </div>
        </div>
      </template>
    </div>
    <!-- 中奖名单 -->
    <Music ref="mp3vue" />
    <div class="list mask flex-column-center" v-show="type == 4">
      <div class="title">
        中奖名单
      </div>
      <div class="user-list">
        <el-scrollbar class="scroll">
          <ul >
            <li v-for="(item, index) in winnerList" class="item" :key="index">
              <!-- <div>{{ index+1 }} </div> -->
              <img :src="item.headImgUrl" alt="">
              <div class="name ellipsis"><span>恭喜 </span> {{ item.nickName }}</div>
              <div class="level"><span>中了 </span> {{ item.level }}</div>
              <div class="tiem">{{ item.luckyTime }}</div>
            </li>
          </ul>
        </el-scrollbar>
      </div>
      <div class="btn main back" @click="type = 2">返回</div>
    </div>
  </div>
</template>

<script>
import SeamlessScroll from '@/components/SeamlessScroll'
import { getRandomUserList,getAllUser, uploadWinner, getWinnerList, getQrcode, test } from '@/api/index'
import websocket from '@/api/ws'
import {debounces} from '@/utils/index.js'
import {testAvatar} from '@/testapi/index.js'
import Music from '@/components/Music'
import gift2 from '@/assets/images/gift2.png'
import gift3 from '@/assets/images/gift3.png'
import gift4 from '@/assets/images/gift4.png'
import gift5 from '@/assets/images/gift5.png'
import gift6 from '@/assets/images/gift6.png'
import gift7 from '@/assets/images/gift7.png'

export default {
  name: "index",
  components: {
    SeamlessScroll,
    Music
  },
  data() {
    return {
      startTest:null,
      openTest:false,//是否开启测试模式
      sessionCode: this.$dayjs().format('YYYYMMDD'),
      type: 1,
      num: 1,
      qrcode: '',
      prizeDrawn: false, // 是否抽过奖
      showUser: [],
      prizeInfo: [
        {
          img: gift2,
          name: '五等奖'
        },
        {
          img: gift3,
          name: '四等奖'
        },
        {
          img: gift4,
          name: '三等奖'
        },
        {
          img: gift5,
          name: '二等奖'
        },
        {
          img: gift6,
          name: '一等奖'
        },
        {
          img: gift7,
          name: '特等奖'
        },
      ],
      prizeIndex: 0,
      startRandomFlag: false,
      lotteryStatus:false,//false：不允许停止抽奖，true：允许停止抽奖
      lotteryTimeDiff:1000,//开始后几秒钟允许停止抽奖
      randonTimer: {},
      listData: [],
      allUserList: [],
      randomUserList: [],
      winnerList: [],
      classOption4: {
        step: 1,
        limitMoveNum: 1,
        direction: 2,
      },
      classOption: {
        direction: 0
      },
      seamlessScroll: true
    };
  },
  watch: {
    type: function(value) {
      if (value == 2) {
        this.getRandomUser()
        this.getWinner()
      }
    }
  },
  created() {
    // 添加测试
    // for (let i=0;i<5;i++) {
    //   const user = {
    //     "id": i+18,
    //     "createTime": "1705989018",
    //     "nickName": "asdasd44"+i,
    //     "openId": "123",
    //     "headImgUrl": 'https://inews.gtimg.com/om_bt/OZ-YJqQkExeFSXrZkTcVrOi4hhIG7kT97mQAHBieXquooAA/641',
    //     "sessionCode": "123"
    //   }
    //   test(user)
    // }

    if (this.$route.query.code) {
      this.sessionCode = this.$route.query.code
    }
    if (this.$route.query.type==='test') {
      this.openTest = true;
    }
    const params = {
      sessionCode: this.sessionCode
    }
    getAllUser(params).then(res => {
      this.allUserList = res.data
    })
    let pas = {
      text: `http://game.sztldt.net/participation?sessionCode=${this.sessionCode}`
    }
    getQrcode(pas).then(res => {
      this.qrcode = res.data
    })
    this.getRandomUser()
    this.getWebSocket()
    this.getWinner()
    this.keydowns()
  },
  methods: {
    // 键盘事件监听
    keydowns(){
      document.addEventListener('keyup',(e)=>{
        if(e.type!=="keyup")return;
          debounces(()=>{
            if(e.key==="Enter"){
                  switch(this.type){
                    case 1:
                      this.type = 2;
                      break;
                    case 2:
                      this.goRandom();
                      break;
                    case 3:
                      if(this.startRandomFlag){
                        this.stopRandom();
                      }else{
                        this.startRandom();
                      }
                      break;
                  }
            }
            if(e.key==="Escape"){
                  switch(this.type){
                    case 2:
                      this.type = 1;
                      break;
                    case 3:
                      if(this.startRandomFlag){
                        this.stopRandom();
                      }else{
                        this.backChoose();
                      }
                      break;
                    case 4:
                      this.type = 2;
                      break;
                  }
            }
          },200)
      })
    },
    async getWebSocket() {
      try{
      let ws =await websocket.Init(this.sessionCode)
      ws.onmessage = this.websocketonmessage
      }catch(err){
        console.log(err);
      }
    },
    //接收到消息的回调函数
    websocketonmessage(res) {
      // e后端传回来参数
      const data = JSON.parse(res.data)
      if (data.type == 1) {
        const text = data.text
        this.allUserList.push(text)
        this.$refs.SeamlessScroll._initMove()
      }
    },
    getRandomUser() {
      const params = {
        sessionCode: this.sessionCode
      }
      getRandomUserList(params).then(res => {
        this.randomUserList = res.data
      })
    },
    getWinner() {
      const params = {
        sessionCode: this.sessionCode
      }
      getWinnerList(params).then(res => {
        this.winnerList = res.data
      })
    },
    changePrize(type) {
      const length = this.prizeInfo.length - 1
      if (type === '+') {
        if (this.prizeIndex >= length) {
          this.prizeIndex = 0
        } else {
          this.prizeIndex++
        }
      } else {
        if (this.prizeIndex <= 0) {
          this.prizeIndex = length
        } else {
          this.prizeIndex--
        }
      }
    },
    goRandom() {
      if (this.prizeDrawn) {
        const users = this.showUser.map(e => this.randomUserList[e].id)
        if (this.randomUserList.length - users.length <= this.num) return this.$message.error(`没中奖的只剩下${this.randomUserList.length}人了哦`);
      } else {
        if (this.randomUserList.length <= this.num) return this.$message.error(`没中奖的只剩下${this.randomUserList.length}人了哦`);
      }
      for(let i=0; i<this.num;i++) {
        this.showUser.push(i)
      }
      this.startRandom()
      this.type = 3
    },
    backChoose() {
      this.type = 2
      this.showUser = []
    },
    startRandom() {
      if (this.prizeDrawn) {
        // 抽过奖，去掉中奖人
        const users = this.showUser.map(e => this.randomUserList[e].id)
        const remainNum = this.randomUserList.length - users.length
        if (remainNum <= this.num) return this.$message.error(`没中奖的只剩下${remainNum}人了哦`);
        const filteredUsers = this.randomUserList.filter(user => !users.includes(user.id));
        this.randomUserList = filteredUsers
      } else {
        this.prizeDrawn = true
        if (this.randomUserList.length <= this.num) return this.$message.error(`没中奖的只剩下${this.randomUserList.length}人了哦`);
      }
      this.startRandomFlag = true
      this.$refs.mp3vue.myplay(1)
      for(let i=0; i<this.num;i++) {
        this.randonTimer[i] = setInterval(() => {
          this.$set(this.showUser, i, this.randomNum())
        }, 100)
      }

      this.lotteryStatus = true;
      setTimeout(()=>{
        this.lotteryStatus = false;
      },this.lotteryTimeDiff)
    },
    randomNum() {
      const max = this.randomUserList.length
      const random = Math.floor(Math.random() * (max))
      // console.log('this.showUser',random, this.showUser,this.showUser.includes(random));
      if (this.showUser.includes(random)) return this.randomNum()
      return random
    },
    stopRandom() {
      if(this.lotteryStatus) return;
      this.$refs.mp3vue.stop(1)
      this.startRandomFlag = false
      this.$refs.mp3vue.myplay(2)
      this.recursionStop(0)
    },
    recursionStop(x) {
      clearInterval(this.randonTimer[x]);
      if (x < this.num-1) {
        // setTimeout(() => {
          this.recursionStop(x+1)
        // }, 500)
      } else {
        this.uploadWinner()
      }
    },
    uploadWinner() {
      // 上传中奖人
      const users = this.showUser.map(e => this.randomUserList[e].id)

      const params = {
        sessionCode: this.sessionCode,
        wechatUserIds: users,
        level: this.prizeInfo[this.prizeIndex].name,
        prizeImg: this.prizeInfo[this.prizeIndex].img
      }
      uploadWinner(params).then(res => {
        console.log(res);

      })
    },
    chooseNum(type) {
      if (type === '+' && this.num < 5) {
        this.num++
      } else if (type === '-' && this.num > 1) {
        this.num--
      }
    },
    testOnClick(){
      if(!this.openTest)return;
      if(this.startTest){
        clearTimeout(this.startTest);
        this.startTest = null;
        return;
      }
      this.addTestUser();
    },
    // 增加测试用户
    addTestUser(){
      let user = '用户';
      const i = Math.floor(Math.random() * testAvatar.length);
        const openid = new Date().getTime();
        const params = {
          "nickName": openid + user,
          "openId": openid,
          "headImgUrl": testAvatar[i],
          "sessionCode": this.sessionCode
        }
        test(params);
        this.startTest = setTimeout(()=>{
          this.addTestUser();
        },2000)
    }
  }
};
</script>

<style lang="scss" scoped>
.btn{
  border-radius:40px;
  padding:0px 20px;
  background:gold;
  font-size: 26px;
  line-height: 50px;
  text-align: center;
  cursor: pointer;;
  &.main{
    width:150px;
  }
  &:hover{
    background:rgba(gold,.8);
  }
  &:active{
    background:gold;
  }
  &.disabled{
    background:#999;
    &:active{
      background:#999;
    }
    &:hover{
      background:#999;
    }
  }
}
.ercode{
  position:absolute;
  z-index:10;
  right:20px;
  top:25%;
  font-size:0;
  border-radius:10px;
  overflow:hidden;
  img{
    width:300px;height:300px;
  }
  p {
    width: 100%;
    margin: 0 auto;
    line-height: 50px;
    background: gold;
    font-weight: 700;
    font-size: 22px;
    text-align:center;
  }
}
.mask{
  width: 100%;
  height: 100vh;
  background: rgba(0,0,0,.4);
  position:relative;
  z-index:2;
}
.bg-box{
  padding-top:8%;
  position:absolute;
  z-index:0;
  width:100%;
  img{
    width:600px;
  }
}
.page {
  position:relative;
  width: 100%;
  height: 100vh;
  font-size: 22px;
  background: url('../assets/images/background-image.jpg') no-repeat ;
  background-size:100% 100%;
  color: white;
  .online {
    position:absolute;
    bottom:40px;
    width:100%;
    .circulate {
    }
    .online-bottom {
      padding:50px 200px 0 ;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .warp {
      width: 100%;
      height: 100px;
      margin: 0px auto;
      overflow: hidden;
      .ul-item {
        list-style: none;
        padding: 0;
        margin: 0 auto;
        display: flex;
          .li-item {
            height: 100px;
            overflow: hidden;
            border-radius: 50%;
            line-height: 100px;
            color: #fff;
            text-align: center;
            font-size: 30px;
            img{
              width: 100px;
              height: 100%;
              margin:0 10px;
              border-radius:50%;
            }
        }
      }
    }
  }
  .start {
    text-align: center;
    padding-top:20px;
    .title-box {
      background: url('../assets/images/title-bg.png') no-repeat 0 0;
      background-size:100% auto;
      padding-top: 20px;
      width:450px;
      height:190px;
      margin:0px auto 0;
      .icon-arrow{
        font-size:30px;
        padding:10px;
        margin:0 40px;
        background:#ff3333;
        border-radius:50%;
      }
      .title{
        line-height:60px;
        font-size: 45px;
        font-weight: bold;
        color:gold;
      }
    }
    .prize {
      img {
        width: 700px;
        height: 700px;
      }
    }
  }
  .roll {
    text-align: center;
    .rotate {
      margin: 0px auto 10px;
      padding:0 50px;
      width: 1200px;
      height:700px;
      background: url('../assets/images/border.png') no-repeat center;
      background-size:100% auto;
      display: flex;
      justify-content: space-evenly;
      .user {
        padding: 10px 0px 0;
        width:160px;
        img {
          width: 140px;
          height: 140px;
          border-radius: 50%;
        }
        .name{
          font-size:24px;
          line-height:2;
          width:160px;
        }
      }
    }
    .roll-back {
      position: absolute;
      right: 100px;
      bottom: 150px;
    }
    .hiddenIpt {
      width: 0;
      opacity: 0;
    }
  }

  .bottom-btn-box{
      padding:0 80px;
      position: fixed;
      right: 0px;
      bottom: 100px;
      width:100%;
      .left {
        .pick {
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 20px;
          .pick-box {
            line-height: 30px;
            border-radius: 5px;
            padding: 4px 10px;
            i {
              font-size: 24px;
              font-weight: 700;
              padding:3px ;
              background: gold;
              border-radius: 5px;
            }
            .num{
              font-size: 34px;
              font-weight: 700;
              padding:0 10px;
              text-align: center;
            }
          }
        }
      }
      .right {
        text-align: center;
        color:gold;
        .bottom {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .back {
          font-size: 18px;
          margin-left:100px;
          color:#fff;
        }
      }
      .center-btn{
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .left,.right {
        width: 400px;
        height:100px;
      }
    }
  // 中奖名单
  .list {
    margin: 0 auto;
    padding: 100px 0 0px;
    .title {
      margin-bottom:80px;
      padding:10px 50px;
      font-size: 30px;
      font-weight: 700;
      text-align: center;
      background: rgba(rgb(252, 227, 88),.8);
      border-radius: 5px;
    }
    .user-list {
      width: 800px;
      background: rgba(rgb(252, 227, 88),.8);
      border-radius: 10px;
      margin-bottom: 80px;
      .scroll{
      }
      .item {
        height: 80px;
        display: flex;
        align-items: center;
        .tips {
        }
        .name {
          width: 250px;
        }
        .level{
          width: 120px;
        }
        .tiem{
          margin-left:40px;
          font-size: 20px;
        }
        span{
          font-size: 22px;
        }
      }
      img {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        margin-left: 20px;
        margin-right: 20px;
      }
    }
    .back{
      position:absolute;
      bottom:100px;
      margin:0 auto;
    }
  }
  .points {
    cursor: pointer;
  }
  .scroll {
    height: 600px;
    overflow-x: hidden !important;
  }
  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
